<template>
  <div class="absolute top-0 left-0 right-0 bottom-0 flex flex-col">
    <div class="pl-4" @click="handleClickCompanyInfo" v-if="!isPC()">
      <div class="flex flex-row w-full items-center py-2 justify-between pr-4">
        <div class="flex flex-row items-center">
          <h2 class="text-[#262626] text-[16px] font-bold mr-1">
            {{ cp_companyName }}
          </h2>
          <van-icon name="arrow" v-if="enableBusinessRule" />
        </div>

        <van-popover
          v-model:show="showMorePopover"
          placement="bottom-end"
          :actions="moreActions"
          @select="onSelectMoreActions"
        >
          <template #reference>
            <Icon
              v-show="!disableManageCustomer"
              size="22"
              @click.stop="showMorePopover = true"
            >
              <MoreHorizFilled />
            </Icon>
          </template>
        </van-popover>
      </div>

      <div class="flex flex-row gap-4 pt-1 pb-[6px]">
        <customTag class="custom-tag" color="#52C41A" v-show="cp_CompanyInfo.stockType">
          {{ cp_CompanyInfo.status }}</customTag
        >
        <customTag class="custom-tag" color="#436BFF" v-show="cp_scale?.length > 0">{{
          cp_scale
        }}</customTag>
        <customTag class="custom-tag" color="#FA8C16" v-show="cp_CompanyInfo.stockType">
          {{ cp_CompanyInfo.stockType }} | {{ cp_CompanyInfo.stockNumber }}</customTag
        >
      </div>
    </div>

    <van-tabs v-model:active="active" sticky class="my-tabs">
      <van-tab :title="item.name" v-for="item in tabs" :key="item.type" color="red">
      </van-tab>
    </van-tabs>

    <div class="flex-auto flex flex-col overflow-auto">
      <competition v-if="cp_item.type === 'competition'" />
      <customerAttend v-if="cp_item.type === 'customerAttend'" />
      <riskIdentification v-if="cp_item.type === 'riskIdentification'" />
      <todo v-if="cp_item.type === 'todo'" />
      <visitRecord v-if="cp_item.type === 'visitRecord'" />
      <meddic v-if="cp_item.type === 'meddic'" />
      <opportunityList v-if="cp_item.type === 'businessOpportunity'" />
    </div>

    <editCustomerView
      title="编辑客户"
      ref="editCustomerRef"
      @create-success="onRefresh"
      :customerId="customerId"
    />
  </div>
</template>

<script setup>
import companyInfo from "../../components/companyInfo/index.vue";
import competition from "../../components/competition/index.vue";
import customerAttend from "../../components/customerAttend/index.vue";
import riskIdentification from "../../components/riskIdentification/index.vue";
import todo from "../../components/todo/index.vue";
import visitRecord from "../../components/visitRecord/index.vue";
import meddic from "../../components/meddic/index.vue";
import opportunityList from "../../components/opportunityList/index.vue";
import customTag from "@/components/customTag.vue";
import editCustomerView from "@/components/customerView/editCustomerView.vue";
import { MoreHorizFilled } from "@vicons/material";
import { Icon } from "@vicons/utils";
import { showLoadingToast, closeToast } from "vant";

import { useRoute, useRouter } from "vue-router";
import { computed, ref, onMounted, nextTick } from "vue";
import { useCommonStore, useCustomerStore } from "@/store";
import { getToken } from "@/utils/auth";
import { getCustomCustomerInfoAPI, removeCustomCustomerAPI } from "@/services/customer";

import { isPC } from "@/utils/platformTool";
import { openPathInNewTab } from "@/utils/urlTool";
import { getUserInfo } from "@/utils/auth";

const commonStore = useCommonStore();
const customerStore = useCustomerStore();

const active = ref(0);
const route = useRoute();
const router = useRouter();

const cp_showComponeyInfo = computed(() => {
  return commonStore.salesCompanyInCustomer;
});

const cp_companyName = computed(() => {
  return customerStore.companyName;
});

const cp_isToB = computed(() => {
  return commonStore.isToB;
});

const cp_enableBusinessOpportunity = computed(() => {
  return commonStore.enableBusinessOpportunity;
});

const cp_item = computed(() => {
  return tabs.value[active.value];
});

const tabs = computed(() => {
  let array = [];
  if (cp_enableBusinessOpportunity.value) {
    array.push({
      name: "商机",
      type: "businessOpportunity",
    });
  }

  array.push({
    name: "预警",
    type: "riskIdentification",
  });

  array.push({
    name: "沟通记录",
    type: "visitRecord",
  });

  if (!cp_enableBusinessOpportunity.value) {
    array.push({
      name: "MEDDIC",
      type: "meddic",
    });
  }

  array.push({
    name: "客户参会人",
    type: "customerAttend",
  });

  array.push({
    name: "待办",
    type: "todo",
  });

  array.push({
    name: "竞争对手",
    type: "competition",
  });

  return array;
});

function changeIndex(index) {
  console.log("changeIndex: ", index);
  active.value = index;
}

const cp_CompanyInfo = computed(() => customerStore.currentCompanyInfo.baseInfo || {});

const cp_scale = computed(() => {
  const map = {
    L: "大型企业",
    M: "中型企业",
    S: "小型企业",
    XS: "微小型企业",
  };
  return map[cp_CompanyInfo.value.scale];
});

function handleClickCompanyInfo() {
  if (!enableBusinessRule.value) {
    return;
  }
  let env = import.meta.env.VITE_ENV;

  let baseUrl = "";
  if (env === "production" || env === "blue") {
    baseUrl = "https://x-mate.com";
  } else {
    baseUrl = "https://test.x-mate.com";
  }
  const companyName = customerStore.companyName;
  const companyId = customerStore.currentCompanyId;
  const token = getToken();
  let url = `${baseUrl}/postmeet-xmate-h5/#/xmateCustomerDetail?companyName=${companyName}&companyId=${companyId}&token=${token}&customerId=${customerId.value}`;
  window.open(url, "_blank");
}

const customCustomerInfo = ref(null);

const customerId = computed(() => customerStore.currentCustomerId);
const disableManageCustomer = ref(false);
onMounted(async () => {
  if (cp_showComponeyInfo.value) {
    customerStore.getCompanyBaseInfoAction();
  }
  disableManageCustomer.value = route.query.myTeam || false;

  customCustomerInfo.value = await getCustomCustomerInfoAPI(
    customerStore.currentCustomerId
  );
  console.log("custom customer info: ", customCustomerInfo.value);

  nextTick(() => {
    const type = route.query.tabType;
    if (type) {
      const index = tabs.value.findIndex((v) => v.type === type);
      if (index > 0 && active.value == 0) {
        changeIndex(index);
      }
    }
  });
});

const showMorePopover = ref(false);
// 1-创建客户,2-导入客户,3-编辑客户,4-删除客户
const enableEditCustomer = computed(
  () => customCustomerInfo.value?.typePermissions.indexOf("3") > -1
);
const enableDeleteCustomer = computed(
  () => customCustomerInfo.value?.typePermissions.indexOf("4") > -1
);

const enableBusinessRule = computed(() => {
  return customCustomerInfo.value?.enableBusinessRule === 1;
});

// 是否为负责人
const isCustomerOwner = computed(() => {
  return customCustomerInfo.value?.salesSsoUserIds === getUserInfo().ssoUserId;
});

// 是否为协同跟进人
const isCustomerFollow = computed(() => {
  return customCustomerInfo.value?.followSsoUserIds.includes(getUserInfo().ssoUserId);
});

const editCustomerRef = ref(null);
const moreActions = computed(() => {
  let array = [];
  if (isCustomerOwner.value || isCustomerFollow.value) {
    array.push({ text: "安排沟通", type: "orderVisit" });
  }
  if (enableEditCustomer.value && isCustomerOwner.value) {
    array.push({ text: "编辑客户", type: "editCustomer" });
  }
  if (enableDeleteCustomer.value && isCustomerOwner.value) {
    array.push({ text: "删除客户", type: "removeCustomer" });
  }
  return array;
});

function onSelectMoreActions(action) {
  const { type } = action;
  if (type === "orderVisit") {
    // 跳转到安排沟通
    const { name = "", customerId = "" } = route.query;
    openPathInNewTab("/orderVisit", {
      name,
      customerId,
    });
    return;
  }
  if (type === "editCustomer") {
    // 编辑客户
    editCustomerRef.value.show();
    return;
  }
  if (type === "removeCustomer") {
    // 删除客户
    doRemoveCustomer();
    return;
  }
  console.log("onSelectMoreActions", action);
}

async function doRemoveCustomer() {
  showLoadingToast();
  await removeCustomCustomerAPI(customerStore.currentCustomerId);
  closeToast();
  try {
    window.flutter_inappwebview.callHandler("onBackPressed");
  } catch (error) {
    router.back();
  }
}
</script>

<style lang="less" scoped>
.container {
  --van-tabs-bottom-bar-color: #436bff;
}

/deep/ .van-tab__text {
  font-size: 14px;
}

/deep/ .van-tabs__wrap {
  border-bottom: 0.5px solid #e9e9e9;
}
</style>
